package com.rabbiter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbiter.common.QueryPageParam;
import com.rabbiter.common.Result;
import com.rabbiter.entity.Task;
import com.rabbiter.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器：任务管理模块
 * </p>
 *
 * @author rabbiter
 */
@RestController
@RequestMapping("/task")
public class TaskController {
    @Autowired
    private TaskService taskService;

    /*
     * 新增任务
     * @author rabbiter
     */
    @PostMapping("/save")
    public Result save(@RequestBody Task task){
        return taskService.save(task)?Result.success():Result.fail();
    }

    /*
     * 更新任务
     * @author rabbiter
     */
    @PostMapping("/update")
    public Result update(@RequestBody Task task){
        return taskService.updateById(task)?Result.success():Result.fail();
    }

    /*
     * 删除任务
     * @author rabbiter
     */
    @GetMapping("/del")
    public Result del(@RequestParam String id){
        return taskService.removeById(id)?Result.success():Result.fail();
    }

    /*
     * 批量删除任务
     * @author rabbiter
     */
    @PostMapping("/batchDelete")
    public Result batchDelete(@RequestBody List<Integer> ids){
        return taskService.removeByIds(ids)?Result.success():Result.fail();
    }

    /*
     * 查询任务列表
     * @author rabbiter
     */
    @GetMapping("/list")
    public Result list(){
        List list = taskService.list();
        return Result.success(list);
    }

    /*
     * 模糊查询：根据输入查询任务并以分页的形式展示
     * @author rabbiter
     */
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        String state = (String)param.get("state");

        Page<Task> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Task> queryWrapper =
                new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name) && !"null".equals(name)){
            queryWrapper.like(Task::getName,name);
        }
        if(StringUtils.isNotBlank(state) && !"null".equals(state)){
            queryWrapper.like(Task::getState,state);
        }

        IPage result = taskService.pageCC(page,queryWrapper);
        return Result.success(result.getRecords(),result.getTotal());
    }
}
